import React, { useEffect, useState } from "react";
import { StyleSheet, View, Text, ScrollView } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { getAllQuestions, getRandomQuestions } from "@/mocks/questions";
import { Question } from "@/types/question";
import { useUserStore } from "@/store/user-store";
import { useTheme } from "@/hooks/useTheme";
import Colors from "@/constants/colors";
import QuestionCard from "@/components/QuestionCard";
import Button from "@/components/Button";
import StatsCard from "@/components/StatsCard";

export default function HomeScreen() {
  const router = useRouter();
  const { colors } = useTheme();
  const {
    answeredQuestions,
    bookmarkedQuestions,
    simulations,
    streakDays,
    updateStreak,
  } = useUserStore();
  const [allQuestions, setAllQuestions] = useState<Question[]>([]);
  const [dailyQuestions, setDailyQuestions] = useState<Question[]>([]);

  // Update streak when app is opened
  useEffect(() => {
    updateStreak();
  }, []);

  // Load all questions and daily questions
  useEffect(() => {
    const loadQuestions = async () => {
      const questions = await getAllQuestions();
      setAllQuestions(questions);
      const daily = await getRandomQuestions(3);
      setDailyQuestions(daily);
    };
    loadQuestions();
  }, []);

  const answeredCount = Object.keys(answeredQuestions).length;
  const totalQuestions = allQuestions.length;
  const completionRate =
    totalQuestions > 0 ? Math.round((answeredCount / totalQuestions) * 100) : 0;
  const averageScore =
    Object.values(answeredQuestions).length > 0
      ? Math.round(
          Object.values(answeredQuestions).reduce(
            (sum, answer) => sum + answer.score,
            0
          ) / Object.values(answeredQuestions).length
        )
      : 0;
  const simulationsCompleted = simulations.length;
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={["bottom"]}>
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.header}>
          <Text style={[styles.greeting, { color: colors.text }]}>你好，开发者！</Text>
          <View style={[styles.streakContainer, { backgroundColor: "rgba(245, 158, 11, 0.1)" }]}>
            <Ionicons name="flame" size={18} color={colors.warning} />
            <Text style={[styles.streak, { color: colors.warning }]}>{streakDays} 天连续学习</Text>
          </View>
        </View>
        <View style={styles.statsContainer}>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.statsScroll}
          >
            <StatsCard
              title="完成率"
              value={`${completionRate}%`}
              subtitle={`${answeredCount}/${totalQuestions} 个问题`}
              icon={<Ionicons name="book-outline" size={16} color={colors.primary} />}
            />
            <StatsCard
              title="平均分数"
              value={`${averageScore}%`}
              subtitle="继续提高！"
              icon={<Ionicons name="ribbon-outline" size={16} color={colors.secondary} />}
            />
            <StatsCard
              title="模拟测试"
              value={simulationsCompleted}
              subtitle="已完成"
              icon={<Ionicons name="time-outline" size={16} color={colors.warning} />}
            />
            <StatsCard
              title="书签"
              value={bookmarkedQuestions.length}
              subtitle="已保存问题"
              icon={<Ionicons name="calendar-outline" size={16} color={colors.success} />}
            />
          </ScrollView>
        </View>
        <View style={styles.actionsContainer}>
          <Button
            title="开始练习"
            onPress={() => router.push("/tabs/practice")}
            icon={<Ionicons name="book-outline" size={16} color={Colors.dark.text} />}
            fullWidth
          />
          <View style={styles.buttonSpacer} />
          <Button
            title="模拟面试"
            onPress={() => router.push("/tabs/simulate")}
            variant="secondary"
            icon={<Ionicons name="play" size={16} color={Colors.dark.text} />}
            fullWidth
          />
        </View>
        <View style={styles.sectionHeader}>
          <Text style={[styles.sectionTitle, { color: colors.text }]}>每日问题</Text>
          <Text style={[styles.sectionSubtitle, { color: colors.subtext }]}>今天练习这些</Text>
        </View>
        {dailyQuestions.map((question) => (
          <QuestionCard key={question.id} question={question} />
        ))}
        <View style={styles.footer} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 24,
  },
  greeting: {
    fontSize: 24,
    fontWeight: "700",
  },
  streakContainer: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 16,
  },
  streak: {
    marginLeft: 6,
    fontSize: 14,
    fontWeight: "600",
  },
  statsContainer: {
    marginBottom: 24,
  },
  statsScroll: {
    paddingRight: 16,
    gap: 12,
  },
  actionsContainer: {
    marginBottom: 24,
  },
  buttonSpacer: {
    height: 12,
  },
  sectionHeader: {
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "700",
    marginBottom: 4,
  },
  sectionSubtitle: {
    fontSize: 14,
  },
  footer: {
    height: 20,
  },
});
